/**
操作pdf的
 */
 ;(function($){
	const MT = 30; //页头偏移
	const MB = 20; //页尾偏移
	const ML= 30; //页左偏移
	const MR=30; //页右偏移
	const PARA_BEFORE = 20; //每个canvas之间的分隔
	
	const TYPE_BREAK = 0;
	const TYPE_CHART = 1;
	const TYPE_DOM = 2;
	
	const TITLE_SIZE = 26; //标题字号
	const TEXT_SIZE = 14;//内容字号
	
	var pdf = null; // jsPDF实例	
	var myoptions = {}; //配置项
	
	var printList = [];//需要打印的对象列表
	var busyTaskCount= 0;//正在处理的任务数
	
	var pdfPageTop =0;//单页距离顶部距离
	var pdfPageWidth = 0; //pdf单页宽度
	var pdfPageHeight = 0; //pdf单页高度
	
	var _defaultOptions = {
			direct: 'l',
			unit: 'px',
			pageType: 'a4',
			title: '报告',
			subject: '',
			keywords: '',
			pageHead: MT,
			pageEnd: MB,
			pageLeft: ML,
			pageRight: MR,
			afterPrint: null
	};
	
	function newPage() {
		pdf.addPage();
		pdfPageTop = myoptions.pageHead;
	}
	
	function pushData(type, obj) {
		var ret= {
			type: type,
			data: obj
		};
		printList.push(ret);
		
		return ret;
	}
	  
	function outputChart(chartCanvas) {
		if (!chartCanvas) {
			return;
		}

		var cw = chartCanvas.width;
		var ch = chartCanvas.height;
		var pw = pdfPageWidth - myoptions.pageLeft - myoptions.pageRight;
		if (cw > pw) {
			//如果画布宽度大于页面宽度
			var scale = pw / cw;
			cw = pw;
			ch = ch * scale;
		}
		//如果画布高度大于页面高度
		var ph = pdfPageHeight - myoptions.pageHead - myoptions.pageEnd;
		if (pdfPageTop > ph) {
			newPage();
		}
		ph = pdfPageHeight - pdfPageTop - myoptions.pageEnd;
		if (ph < ch && (ph + (myoptions.pageEnd / 2)) < ch) {
			//如果剩余页面高度小于实际尺寸了,则压缩高度
			var scale = ph / ch;
			ch = ph;
			cw = cw * scale;
		}

		var left = Math.floor((pdfPageWidth - cw) / 2);
		pdf.addImage(chartCanvas.toDataURL(), "JPEG", left, pdfPageTop, cw, ch);
		pdfPageTop += PARA_BEFORE + ch;
		
	};
    
	function outputDom(canvas) {
		var canvasWidth = canvas.width;
		var canvasHeight = canvas.height;
		var ph = pdfPageHeight - myoptions.pageHead - myoptions.pageEnd;
		//根据画布宽度和pdf页的宽度来计算缩放比例
		var pw = pdfPageWidth - myoptions.pageLeft - myoptions.pageRight;
		var scale = canvasWidth <= pw ? 1 : canvasWidth / pw;
		var trueWidth = scale == 1 ? canvasWidth : pw;
		//根据比例计算pdf单页高度对应到画布的实际单页高度
		var canvasOffset = 0;

		while (canvasOffset < canvasHeight) {
			var pdfBlankHeight = ph - pdfPageTop;
			var cavansRangeHeight = pdfBlankHeight * scale;

			var canvasCopyHeight = Math.min(cavansRangeHeight, canvasHeight - canvasOffset);

			var copyCanvas = document.createElement('canvas');
			copyCanvas.width = canvasWidth,
				copyCanvas.height = canvasCopyHeight;
			var ctx = copyCanvas.getContext('2d');
			ctx.drawImage(canvas, 0, canvasOffset, canvasWidth, canvasCopyHeight, 0, 0, canvasWidth, canvasCopyHeight);

			var pdfCopyHeight = canvasCopyHeight / scale;
			pdf.addImage(copyCanvas.toDataURL('image/jpeg', 1.0), 'JPEG', myoptions.pageLeft, pdfPageTop, trueWidth, pdfCopyHeight);

			canvasOffset += canvasCopyHeight;

			pdfPageTop += pdfCopyHeight;
			if (pdfPageTop + 10 >= ph) {
				pdf.addPage();
				pdfPageTop = myoptions.pageHead;
			}
		}
	}
		
	var PdfCanvas = function(options){
		myoptions = Object.assign(_defaultOptions, options);
		pdf = new jsPDF(myoptions.direct, myoptions.unit, myoptions.pageType);
		pdf.setFont("fangsong");

		pdfPageTop = myoptions.pageHead;
		pdfPageWidth = pdf.internal.pageSize.getWidth();
		pdfPageHeight = pdf.internal.pageSize.getHeight();

		pdf.setProperties({
			title: myoptions.title,
			subject: myoptions.subject,
			keywords: myoptions.keywords,
			author: 'alangyun',
			creator: '专业化评价预警工具'
		})
		pdf.setFontSize(TITLE_SIZE);
		pdf.text(myoptions.title, pdfPageWidth / 2, pdfPageTop, { align: 'center' });
		pdfPageTop += PARA_BEFORE;
		pdf.setFontSize(TEXT_SIZE);

		return {
			options: myoptions,
			pdf: pdf,
			addChart: $.proxy(this.addChart, this),
			addDom: $.proxy(this.addDom, this),
			print: $.proxy(this.print, this),
			addPageBreak: $.proxy(this.addPageBreak, this)
		};
	};
	
	PdfCanvas.prototype.addPageBreak = function(){
		pushData(TYPE_BREAK, null);
	}
	
	PdfCanvas.prototype.addChart = function(chartCanvas) {
		pushData(TYPE_CHART, chartCanvas);
	};	
    
	PdfCanvas.prototype.addDom = function(domTable) {
		const item= pushData(TYPE_DOM, null);
		busyTaskCount++;
        html2canvas(domTable, {
            background: "#FFFFFF",//如果指定的div没有设置背景色会默认成黑色,这里是个坑
            useCORS: true
        }).then(canvas => {
	        item.data = canvas;
        }).finally(() => {
	        busyTaskCount--;
		})
        	
	}
	
	PdfCanvas.prototype.print= function(fileName){
		if (printList.length == 0) {
			return;
		}
		var cycle = 0;
		var interval = setInterval(function() {
			if (busyTaskCount <= 0) {
				clearInterval(interval);
				console.log(printList);
				printList.forEach(item => {
					if (item.type === TYPE_BREAK) {
						newPage();
					} else if (item.type === TYPE_DOM) {
						outputDom(item.data);
					} else if (item.type === TYPE_CHART) {
						outputChart(item.data);
					}
				})

				var f = myoptions.title + "_" + Date.now() + ".pdf";
				if (fileName) {
					f = fileName;
				}
				pdf.save(f);
				if(myoptions.afterPrint){
					myoptions.afterPrint.call();
				}
			} else {
				if (++cycle > 20) {
					clearInterval(interval);
					throw new Error("处理超时！");
				}
			}
		}, 500);
	}
	
	// 调用该方法获取实例
	$.fn.pdfcanvas = function(options){
		return new PdfCanvas(options);
	}
	
})(jQuery);